package net.jjjshop.common.util.buer;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.resource.ResourceUtil;
import cn.hutool.core.lang.UUID;
import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import com.aspose.words.Document;
import com.aspose.words.ImageSaveOptions;
import com.aspose.words.SaveFormat;
import com.deepoove.poi.XWPFTemplate;
import lombok.SneakyThrows;
import org.apache.commons.lang3.RandomStringUtils;

import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class OssService {

    public static String upload(String filePath) {

        String endpoint = "oss-cn-shanghai.aliyuncs.com";
        String accessKeyId = "LTAI5tDxRxZMvxEYmeU6S3eh";
        String accessKeySecret = "WKxTWk8SgI3zNGD07urQY1NDTYavnO";
        String bucketName = "shouwei";
        String name = filePath.substring(filePath.lastIndexOf("/") + 1);
        String objectName = "approve_files/" + getYMDHMS() + RandomStringUtils.randomAlphanumeric(4) + "/" + name;

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        try {
            FileInputStream fis = new FileInputStream(filePath);

            // 创建PutObjectRequest对象。
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, fis);

            // 设置该属性可以返回response。如果不设置，则返回的response为空。
            putObjectRequest.setProcess("true");
            // 上传字符串。
            PutObjectResult result = ossClient.putObject(putObjectRequest);
            // 如果上传成功，则返回200。
            System.out.println(result.getResponse().getStatusCode());

        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        return BuerConfig.ossUrl+objectName;
    }

    public static String getYMDHMS() {
        final Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        return sdf.format(calendar.getTime());
    }

  /*@SneakyThrows
    public static void main(String[] args) {
        String path = generateImage("站三");
        System.out.println(path);
    }*/

   @SneakyThrows
   static String generateImage(String username) throws Exception {
//       File file = FileUtil.file(BuerConfig.temppcthUrl+BuerConfig.temppcthUrlword);
//       InputStream in = new FileInputStream(file);
       // 读取resources文件下 Word 模板文件
//       URL resource = ResourceUtil.getResource(BuerConfig.temppcthUrlword);
       InputStream in = ResourceUtil.getStream("config/" + BuerConfig.temppcthUrlword);
       // 使用模板引擎将模板渲染，并传入一个数据映射表 initWordMap()。
       XWPFTemplate template = XWPFTemplate.compile(in).render(initWordMap(username));
        //不存在则创建目录
        FileUtil.mkdir(BuerConfig.pcthUrl);
        String wordname = UUID.randomUUID().toString();

        // 上传路径Users/admin/project/logs/valueguard/uploadPath/cert/test.docx
        String tmpFilePath = BuerConfig.pcthUrl+ "/"+wordname+".docx";
        // 填充完数据后保持到上面路径
        template.writeToFile(tmpFilePath);

        // 上传保存到/Users/admin/project/logs/valueguard/uploadPath/cert/test.jpeg
        String jpgFilePath = BuerConfig.pcthUrl+ "/"+wordname+".jpeg";
        // 打开生成的 Word 文件
        Document doc = new Document(new FileInputStream(new File(tmpFilePath)));
        // 方式一：直接用这个生成图片，分辨率相对ok。
        //doc.save(jpgFilePath,SaveFormat.JPEG);

        // 2.对图片分辨率要求高的，使用以下对象ImageSaveOptions去调。图片相对会比较高清
        // 保存呈现的文档页面或形状的格式，可以是栅格SaveFormat.PNG, SaveFormat.BMP, SaveFormat.JPEG或矢量SaveFormat.SVG.
        ImageSaveOptions saveOptions = new ImageSaveOptions(SaveFormat.PNG);
        // 设置生成图像的水平分辨率，以每英寸点数为单位
        saveOptions.setHorizontalResolution(300F);
        // 为生成的图像设置水平和垂直分辨率，以每英寸点数为单位
        saveOptions.setResolution(212.7F);
        doc.save(jpgFilePath, saveOptions);

      /*  int dirLastIndex = ValueGuardConfig.getProfile().length() + 1;
        // 截取cert/test.jpeg
        String currentDir = StringUtils.substring(jpgFilePath, dirLastIndex);
        // 拼接路径
        String imagesPath = "http://localhost:8015" + Constants.RESOURCE_PREFIX + "/" + currentDir;
        System.out.println(imagesPath);
        */
        return upload(BuerConfig.pcthUrl + "/" + wordname + ".jpeg");
    }

    /**
     * word文档需要填充的数据
     *
     * @return
     */
    private static Map<String, Object> initWordMap(String username) {
        Map<String, Object> map = new HashMap<>();
        map.put("username", username);
        map.put("companyname", BuerConfig.companyName);
        map.put("date", DatePattern.CHINESE_DATE_FORMAT.format(new Date()));
        return map;
    }


}
